package org.example.gradlegateway.filter;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * 定义 单一 filter
 * 在gatewayServer项目中新建自定义Filter Factory类MyGatewayFilterFactory。类名的后缀必须是GatewayFilterFactory。所以这里创建的是一个My Gateway Filter
 * 类继承AbstractGatewayFilterFactory
 * 实现无参构造器，调用父类的构造器
 * 实现一个配置类MyGatewayFilterFactory.Config，定义需要添加前缀的reponse header key responseHeaderKey和给reponse header value添加的前缀responseHeaderPrefixValue
 * 重写父类的apply方法，实现匹配reponse header的key和给reponse header的value添加前缀的逻辑
 * 重写父类的shortcutFieldOrder方法，让其支持shortcut语法
 */
@Slf4j
@Component
public class MyDemoGatewayFilterFactory extends AbstractGatewayFilterFactory<MyDemoGatewayFilterFactory.KeyValueConfig> {


    //表示过滤器要接收到一个什么类型的参数才能正常运行
    public MyDemoGatewayFilterFactory() {
        super(MyDemoGatewayFilterFactory.KeyValueConfig.class);
    }


    @Setter
    @Getter
    public static class KeyValueConfig {
        private String customKey;

        private String customValue;
    }

    @Override
    public GatewayFilter apply(KeyValueConfig config) {
        return (exchange, chain) -> {
            exchange.getResponse().getHeaders().add("X-Response-Custom-Key", config.getCustomKey());
            exchange.getResponse().getHeaders().add("X-Response-Custom-value", config.getCustomValue());
            return chain.filter(exchange);
        };
    }


    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("customKey", "customValue");
    }


}